package spider

import (
	"time"
)

var DayJueMap = make(map[string]map[string]bool) // 日决算标记
// 标记
func tag(date, channelName string, b bool) {
	if _, ok := DayJueMap[date]; !ok {
		DayJueMap = make(map[string]map[string]bool)
	}
	if len(DayJueMap[date]) == 0 {
		DayJueMap[date] = make(map[string]bool)
	}
	if !DayJueMap[date][channelName] {
		DayJueMap[date][channelName] = b
	}
}

// 是否全部完成
func isDone(date string) bool {
	if len(DayJueMap[date]) == 0 {
		return false
	}
	for _, b := range DayJueMap[date] {
		if !b {
			return false
		}
	}
	return true
}

type Account struct {
	UserName string
	PassWord string
}

type DouYinAccount struct {
	UserName string
	PassWord string
	UserName2 string
	PassWord2 string
	Company	  string
	DouYinCookie 	  string
}



/*******************************抖音平台爬虫驱动***********************************/
type DouYinDriver struct {
	Accounts    []DouYinAccount
	Spider      []*DouYinSpider
	ChannelName string
}

func NewDouYinDriver() *DouYinDriver {
	return &DouYinDriver{ChannelName: "抖音"}
}
func (t *DouYinDriver) AddAccount(userName, passWord, userName2, passWord2, Company, DouYinCookie string) {
	t.Accounts = append(t.Accounts, DouYinAccount{
		UserName: userName,
		PassWord: passWord,
		UserName2: userName2,
		PassWord2: passWord2,
		Company:  Company,
		DouYinCookie:  DouYinCookie,
	})
}
func (t *DouYinDriver) isFinish(date string) bool {
	for _, v := range t.Spider {
		if !v.GetDone(date) {
			return false
		}
	}
	return true
}
func (t *DouYinDriver) Run() error {
	for _, a := range t.Accounts {
		v, err := NewDouYinSpider(a.UserName, a.PassWord,a.UserName2, a.PassWord2,a.Company,a.DouYinCookie)
		if err != nil {
			return err
		}
		v.Run()
		t.Spider = append(t.Spider, v)
	}
	// 间隔20分钟爬取一次
	go func() {
		for {
			// 存入日决算标记
			date := time.Now().Add(-24 * time.Hour).Format("2006-01-02")
			tag(date, t.ChannelName, false)
			for _, v := range t.Spider {
				v.Post(true)
			}
			time.Sleep(5 * time.Minute)
			if t.isFinish(date) {
				//db.SaveMsg(date, t.ChannelName)
				// 存入日决算标记
				tag(date, t.ChannelName, true)

			}
			// 判断是否全部完成
			if isDone(date) {
				//db.SaveMsg(date, "日决算")
			}
			time.Sleep(15 * time.Minute)
		}
	}()
	return nil
}
